<?php


namespace Yond\LaravelDomain\Console;

use Illuminate\Support\Str;
use Symfony\Component\Process\Process;

class InstallCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'yond:domain:install {--stack= : The development stack that should be installed (blade,react,vue)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Install the Domain scaffolding';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $stack = $this->optionOrChoice('stack', 'Please choice the development stack that should be installed', ['blade', 'react', 'vue']);

        if ($stack === 'vue') {
            $this->installInertiaVueStack();
        }

        if ($stack === 'react') {
            $this->installInertiaReactStack();
        }

        $this->configDomain();

        $this->info('Domain scaffolding installed successfully.');
    }

    protected function configDomain()
    {
        copy(__DIR__. '/../../config/yond-domain.php', $this->laravel->configPath('yond-domain.php'));

        $domain_path = $this->laravel->basePath('domain');

        $this->files->ensureDirectoryExists($domain_path);

        $this->updateJsonFile('composer.json', 'autoload.psr-4', function ($data) use ($domain_path) {
            return array_merge($data, ['Domain\\' => 'domain/']);
        } );

        exec("composer dump-autoload -d " . $this->laravel->basePath());
    }

    /**
     * Install the Inertia Vue Breeze stack.
     *
     * @return void
     */
    protected function installInertiaVueStack()
    {
        // NPM Packages...
        $this->updateNodePackages(function ($packages) {
            return [
                    '@inertiajs/inertia' => '^0.9.2',
                    '@inertiajs/inertia-vue3' => '^0.4.7',
                    '@inertiajs/progress' => '^0.2.4',
                    'autoprefixer' => '^10.2.4',
                    'postcss' => '^8.2.13',
                    'postcss-import' => '^14.0.1',
                    'vue' => '^3.0.5',
                    'vue-loader' => '^16.1.2',
                ] + $packages;
        });

        $this->setupInertia();
        copy(__DIR__.'/../../stubs/inertia/resources/js/vue.js', resource_path('js/app.js'));
    }

    /**
     * Install the Inertia React Breeze stack.
     *
     * @return void
     */
    protected function installInertiaReactStack()
    {
        // NPM Packages...
        $this->updateNodePackages(function ($packages) {
            return [
                    '@inertiajs/inertia' => '^0.9.2',
                    '@inertiajs/inertia-react' => '^0.6.2',
                    '@inertiajs/progress' => '^0.2.4',
                    'autoprefixer' => '^10.2.4',
                    'postcss' => '^8.2.13',
                    'postcss-import' => '^14.0.1',
                    'react' => '^17.0.2',
                    'react-dom' => '^17.0.2',
                    '@babel/preset-react' => '^7.13.13',
                ] + $packages;
        });

        $this->setupInertia();
        copy(__DIR__.'/../../stubs/inertia/resources/js/react.js', resource_path('js/app.js'));

        $this->replaceInFile('.vue()', '.react()', base_path('webpack.mix.js'));
    }

    protected function setupInertia()
    {
        // Install Inertia...
        $this->requireComposerPackages('inertiajs/inertia-laravel:^0.4.2', 'tightenco/ziggy:^1.0');
        copy(__DIR__ . '/../../stubs/inertia/app/Http/Controllers/InertiaController.stub', app_path('Http/Controllers/InertiaController.php'));

        // Middleware...
        $this->installMiddlewareAfter('SubstituteBindings::class', '\App\Http\Middleware\HandleInertiaRequests::class');

        copy(__DIR__.'/../../stubs/inertia/app/Http/Middleware/HandleInertiaRequests.php', app_path('Http/Middleware/HandleInertiaRequests.php'));

        // Views...
        copy(__DIR__.'/../../stubs/inertia/resources/views/app.blade.php', resource_path('views/app.blade.php'));

        // Components + Pages...
        $this->files->ensureDirectoryExists(resource_path('js/Components'));
        $this->files->ensureDirectoryExists(resource_path('js/Layouts'));
        $this->files->ensureDirectoryExists(resource_path('js/Pages'));

        // Webpack...
        copy(__DIR__.'/../../stubs/inertia/webpack.mix.js', base_path('webpack.mix.js'));
        copy(__DIR__.'/../../stubs/inertia/webpack.config.js', base_path('webpack.config.js'));
        copy(__DIR__.'/../../stubs/inertia/jsconfig.json', base_path('jsconfig.json'));
        copy(__DIR__.'/../../stubs/inertia/resources/css/app.css', resource_path('css/app.css'));
    }



    /**
     * Install the middleware to a group in the application Http Kernel.
     *
     * @param  string  $after
     * @param  string  $name
     * @param  string  $group
     * @return void
     */
    protected function installMiddlewareAfter($after, $name, $group = 'web')
    {
        $httpKernel = file_get_contents(app_path('Http/Kernel.php'));

        $middlewareGroups = Str::before(Str::after($httpKernel, '$middlewareGroups = ['), '];');
        $middlewareGroup = Str::before(Str::after($middlewareGroups, "'$group' => ["), '],');

        if (! Str::contains($middlewareGroup, $name)) {
            $modifiedMiddlewareGroup = str_replace(
                $after.',',
                $after.','.PHP_EOL.'            '.$name.',',
                $middlewareGroup,
            );

            file_put_contents(app_path('Http/Kernel.php'), str_replace(
                $middlewareGroups,
                str_replace($middlewareGroup, $modifiedMiddlewareGroup, $middlewareGroups),
                $httpKernel
            ));
        }
    }

    /**
     * Installs the given Composer Packages into the application.
     *
     * @param  mixed  $packages
     * @return void
     */
    protected function requireComposerPackages($packages)
    {
        $command = array_merge(
            ['composer', 'require'],
            is_array($packages) ? $packages : func_get_args()
        );

        (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1']))
            ->setTimeout(null)
            ->run(function ($type, $output) {
                $this->output->write($output);
            });
    }

    /**
     * Update the "package.json" file.
     *
     * @param  callable  $callback
     * @param  bool  $dev
     * @return void
     */
    protected static function updateNodePackages(callable $callback, $dev = true)
    {
        $configurationKey = $dev ? 'devDependencies' : 'dependencies';

        self::updateJsonFile('package.json', $configurationKey, $callback);
    }

    protected static function updateJsonFile($fileName, $key, callable $callback)
    {
        $file = base_path($fileName);
        if (! file_exists($file)) {
            return;
        }

        $content = json_decode(file_get_contents($file), true);

        $origData = data_get($content, $key);

        $data = $callback($origData??[]);

        ksort($data);

        data_set($content, $key, $data);

        file_put_contents(
            $file,
            json_encode($content, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
        );
    }

    /**
     * Replace a given string within a given file.
     *
     * @param  string  $search
     * @param  string  $replace
     * @param  string  $path
     * @return void
     */
    protected function replaceInFile($search, $replace, $path)
    {
        file_put_contents($path, str_replace($search, $replace, file_get_contents($path)));
    }
}